package net.qiqbframework.modelling.domain;

import net.qiqbframework.common.utils.ReflectionUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;

public class AnnotatedMethodBizIdentifierModel implements BizIdentifierModel<Object> {

    private final Member member;

    private final EntityModel<?> aggregateModel;

    public AnnotatedMethodBizIdentifierModel(Member member, AggregateModel<?> aggregateModel) {
        this.member = member;
        this.aggregateModel = aggregateModel;

    }

    public AnnotatedMethodBizIdentifierModel(AggregateModel<?> aggregateModel) {
        this.member = null;
        this.aggregateModel = aggregateModel;

    }


    @Override
    public String modelName() {
        if (member instanceof Method method) {
            return method.getName();
        }
        if (member instanceof Field field) {
            return field.getName();
        }
        return null;
    }

    @Override
    public Class<?> bizIdentifierType() {
        if (member instanceof Method method) {
            return method.getReturnType();
        }
        if (member instanceof Field field) {
            return field.getType();
        }
        return null;
    }

    @Override
    public Member getMember() {
        return member;
    }

    @Override
    public Object bizIdentifier(Object aggregate) {
        if (aggregate instanceof Aggregate<?> a) {
            return ReflectionUtil.getMemberValue(member, a.aggregateRoot());
        }
        return ReflectionUtil.getMemberValue(member, aggregate);
    }

    @Override
    public EntityModel<?> entityModel() {
        return aggregateModel;
    }
}
